#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
Created on 18-1-2
@author: yzw
@desc:
"""
from django.http import HttpResponse
from django.shortcuts import render
from blog_yzw.blog_app.models import *
from blog_yzw.blog_app.utils import md5
import datetime


# 登录跳转
def turn_login(request):
	return render(request, 'login.html')


# 注册跳转
def turn_register(request):
	return render(request, 'register.html')


# 登录处理
def handle_login(request):
	if 'phone' in request.POST:
		phone = request.POST['phone']
	else:
		return HttpResponse('请输入用户')
	if 'password' in request.POST:
		password = request.POST['password']
	else:
		return HttpResponse('请输入密码')
	object_user = User.objects.filter(phone=phone, status='1')[0:1]
	if object_user.exists():
		for user in object_user:
			if phone == user.phone and user.password == md5(password):
				# 将用户信息存入session
				request.session['phone'] = phone
				request.session['name'] = user.name
				# 修改登录时间
				user.last_login_time = datetime.datetime.now()
				user.save()
				return render(request, 'backstage_index.html', {'name': user.name})
			else:
				context = {'msg': '用户名和密码不匹配'}
				return render(request, 'login.html', context)
	else:
		context = {'msg': '号码未注册或审核异常'}
		return render(request, 'login.html', context)
	return render(request, 'login.html')


# 登出
def logout(request):
	try:
		del request.session['phone']
		del request.session['name']
	except KeyError:
		pass
	return render(request, 'index.html')
